package cz.spock.cms.service;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cz.spock.cms.entity.Node;
import cz.spock.cms.entity.Project;
import cz.spock.core.service.BaseService;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * main service class
 * provides methods like getResponse
 * 
 * @author miso
 *
 */
@Service
public class CmsService extends BaseService {
    
    @Autowired
    private ProjectService pService;
    @Autowired
    private FreeMarkerService fmService;
    @Autowired
    private NodeService nService;
    @Autowired
    private TemplateSourceService tsService;

    /**
     * main method
     * 
     * @param project - first part of url which represents project
     * @param url - WHOLE url (because nodes are recognized only by whole urls)
     */
    public void process(String project, String url, OutputStream output) {
        Project p = pService.findProjectByUrl(project);
        if(p == null) {
            // TODO project not found
            System.out.println("project is null");
        }
        System.out.println("finding by url: " + url);
        Node n = nService.findNodeByUrl(url);
        if(n == null) {
            // TODO node not found
            System.out.println("node is null");
        }
        Map<String, Object> tree = nService.getDataTree(n);
        Map<String, Object> fullTree = nService.getFullDataTree(n);

        System.out.println(tsService.getTemplateSourceById(n.getTemplate().getId()).getTemplate());
        
        Template t = fmService.findTemplateByName(tsService.getTemplateSourceById(n.getTemplate().getId()).getName());

//        Writer out = new BufferedWriter(new OutputStreamWriter(System.out));
        try {
            if(tree == null || fullTree == null) {
                System.out.println("CMSService.process: Tree or fullTree is null.");
                return;
            }
            if(output == null) {
                System.out.println("CMSService.process: OutputStream error");
            }
            t.process(fullTree, new OutputStreamWriter(output));
            System.out.println("process method done.");
//            out.flush();
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }
//        return out;
    }
    
}
